package com.qdu.controller;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.qdu.entity.Examineinfo;
import com.qdu.entity.Houseinfo;
import com.qdu.entity.Userinfo;
import com.qdu.service.ExamineService;
import com.qdu.service.HouseService;
import com.qdu.service.ReportService;
import com.qdu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/houses")
public class HouseController {

    @Autowired
    private HouseService houseService;

    @Autowired
    private ExamineService examineService;

    @Autowired
    private ReportService reportService;

    @Autowired
    private UserService userService;

    @PostMapping("/delete")
    public void deleteByHid(String hid){
        houseService.deleteByPrimaryKey(hid);
    }

    @PostMapping("/add")
    @JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8")
    public Result addHouse(Houseinfo houseinfo, List<MultipartFile> files, HttpServletRequest req){
        Result result=new Result();
        Map<String,Object> results = new HashMap<>();
        String url="";
//        String filePath = "";
//        System.out.println(record);
//        System.out.println(files[0].getOriginalFilename());
        for (MultipartFile file : files){
            System.out.println(file.getOriginalFilename());
            SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
            String originName = file.getOriginalFilename();
            System.out.println(originName);

            String format = sdf.format(new Date());

            String realPath = req.getServletContext().getRealPath("/") + format;
            System.out.println(realPath);

            File folder = new File(realPath);
            if(!folder.exists()){
                folder.mkdirs();
            }
            String newName = UUID.randomUUID().toString() + ".jpg";
            try {
                file.transferTo(new File(folder, newName));
                url = url + req.getScheme() + "://" + InetAddress.getLocalHost().getHostAddress() + ":" + req.getServerPort() + req.getContextPath() + format + newName+"!";
//                url =url+req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() +"/lease_house"+ format + newName+"!";
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        houseinfo.setHimg(url);
        houseinfo.setTag("tag");
        houseinfo.setHtitle(houseinfo.getHmode()+" "+houseinfo.getHestate()+" "+houseinfo.getHtype()+" "+houseinfo.getHorientation());
        houseinfo.setLoaction("location");
        houseinfo.setGoodhouse(false);
        houseinfo.setHreleasedate(new Date());
        houseService.insert(houseinfo);
        System.out.println(url);
//        results.put("status", "success");
//        results.put("url", url);

        result.setStatus(true);
        result.setMsg("房屋上传成功！");
        Examineinfo examineinfo=new Examineinfo();
        examineinfo.setAid("-1");
        examineinfo.setHid(houseinfo.getHid());
        examineinfo.setState(2);
        examineinfo.setUid(houseinfo.getUid());
        examineService.insert(examineinfo);

        return result;
    }

    @PostMapping("/addSelective")
    public void addHouseSelective(Houseinfo record){
        houseService.insertSelective(record);
    }

    @GetMapping("/getAll")
    public List getAll(){
        List<Houseinfo> houses = houseService.getAll();
        ArrayList infos = new ArrayList<>();
        int cnt = 0;
        for(Houseinfo house : houses){
            Map map = new HashMap();
            List<String> imgs=new ArrayList<>();
            String img=house.getHimg();
            String[] is=img.split("!");
            for (String i:is){
                imgs.add(i);
            }
            map.put("house", house);
            map.put("img",imgs.get(0));
            infos.add(map);
            cnt++;
            if(cnt >= 6){
                break;
            }
        }

        return infos;
    }


    @GetMapping("/goodHouse")
    public List goodHouse(){
        List<Houseinfo> houses = houseService.getAll();
        ArrayList infos = new ArrayList<>();
        int cnt = 0;
        for(Houseinfo house : houses){
            if(house.getGoodhouse() == true){
                Map map = new HashMap();
                List<String> imgs=new ArrayList<>();
                String img=house.getHimg();
                String[] is=img.split("!");
                for (String i:is){
                    imgs.add(i);
                }
                map.put("house", house);
                map.put("img", imgs.get(0));
                infos.add(map);
                cnt++;
                if(cnt >= 6){
                    break;
                }
            }
        }

        return infos;
    }

    @GetMapping("/notgoodHouse")
    public List notgoodHouse(){
        List<Houseinfo> houses = houseService.getAll();
        ArrayList infos = new ArrayList<>();
        int cnt = 0;
        for(Houseinfo house : houses){
            if(house.getGoodhouse() == false){
                Map map = new HashMap();
                List<String> imgs=new ArrayList<>();
                String img=house.getHimg();
                String[] is=img.split("!");
                for (String i:is){
                    imgs.add(i);
                }
                map.put("house", house);
                map.put("img", imgs.get(0));
                infos.add(map);
                cnt++;
                if(cnt >= 6){
                    break;
                }
            }
        }

        return infos;
    }

    @GetMapping("/getbykey")
    public List getByKey(String keys){
        List<Houseinfo> houseinfos=houseService.selectByKey(keys);

        return houseinfos;
    }

    @PostMapping("/getbylotskeys")
    public List getByLotsKeys(@RequestBody Map map){
        String mode = map.get("mode").toString();
        int pricelow = Integer.parseInt(map.get("pricelow").toString());
        String type = map.get("type").toString();
        int term = Integer.parseInt(map.get("term").toString());
        int floorlow = Integer.parseInt(map.get("floorlow").toString());
        List<Houseinfo> houseinfos=houseService.selectByLotsKeys(mode,pricelow,type,term,floorlow);

        List<Map> infos=new ArrayList<>();
        List<String> imgs=new ArrayList<>();
        for(Houseinfo h : houseinfos){
            HashMap info = new HashMap<String, Object>();
            String img=h.getHimg();
            String[] is=img.split("!");
            for (String i:is){
                imgs.add(i);
            }
            info.put("house", h);
            info.put("img", imgs.get(0));
            infos.add(info);
        }
        return infos;
    }

    @GetMapping("/getbyhid")
    public Map getByHid(String hid){
        Houseinfo houseinfo = houseService.selectByHid(hid);
        Map<String, Object> result = new HashMap<String,Object>();
        List<String> imgs=new ArrayList<>();
        Userinfo userinfo = userService.selectByPrimaryKey(houseinfo.getUid());

        String img=houseinfo.getHimg();
        String[] is=img.split("!");
        for (String i:is){
            imgs.add(i);
        }
        result.put("house", houseinfo);
        result.put("imgs", imgs);
        result.put("user", userinfo);

        return result;
    }

    @GetMapping("/getbyuid")
    public List selectByUid(String uid){
        List<Map> infos=new ArrayList<>();
        List<Houseinfo> houses=houseService.selectByUid(uid);
        for(Houseinfo h : houses){
            List<String> imgs=new ArrayList<>();
            HashMap info = new HashMap<String, Object>();
            String img=h.getHimg();
            String[] is=img.split("!");
            for (String i:is){
                imgs.add(i);
            }
            Examineinfo examineinfo = examineService.selectByUidAndHid(uid, h.getHid());
            info.put("house", h);
            info.put("examine", examineinfo);
            info.put("img", imgs.get(0));
            infos.add(info);
        }
        return infos;
    }

    @PostMapping("/updateSelective")
    public void updateByPrimaryKeySelective(Houseinfo record){
        houseService.updateByPrimaryKeySelective(record);
    }

    @PostMapping("/update")
    public void updateByPrimaryKey(Houseinfo record){
        houseService.updateByPrimaryKey(record);
    }

    @GetMapping("/getAdoptMessages")
    public Map<String, Object> getAdoptMessages(Integer pageNow,Integer pageSize){
        HashMap<String,Object> result=new HashMap<>();
        List<Map> infos=new ArrayList<>();

        pageNow = pageNow == null ? 0 : pageNow;
        pageSize = pageSize == null ? 6 : pageSize;

        for(Houseinfo h:houseService.getHouseByPage(pageNow,pageSize)){
            HashMap<String, Object> houseInfo=new HashMap<>();
            if(examineService.selectByHid(h.getHid()).getState()==1
                    && (reportService.selectByHid(h.getHid())==null || reportService.selectByHid(h.getHid()).getState()!=3) ){
                Userinfo userinfo=userService.selectByPrimaryKey(h.getUid());
                houseInfo.put("house", h);
                houseInfo.put("user", userinfo);
                infos.add(houseInfo);
            }
        }

        Long totals=houseService.findTotals();

        result.put("houses",infos);
        result.put("total",totals);
        return result;
    }

    @PostMapping("/getimgsbyhid")
    public HashMap<String, Object> getImgsByHid(String hid){
        List<String> imgs=new ArrayList<>();
        HashMap<String,Object> result=new HashMap<>();
        Houseinfo houseinfo=houseService.selectByHid(hid);
        String img=houseinfo.getHimg();
        String[] is=img.split("!");
        for (String i:is){
            imgs.add(i);
        }
        result.put("house",houseinfo);
        result.put("imgs",imgs);
        return result;
    }

    @RequestMapping("/multipleImageUpload")
    public List multipleImageUpload(@RequestParam("uploadFiles") MultipartFile[] files){
        System.out.println("上传的图片数量："+files.length);

        List<Map<String,Object>> root=new ArrayList<>();

        for (MultipartFile file : files) {    //循环保存文件

            Map<String,Object> result=new HashMap<String, Object>();//一个文件上传的结果
            String result_msg="";//上传结果信息

            if (file.getSize() / 1000 > 10000){
                result_msg="图片大小不能超过10M";
            }
            else{
                //判断上传文件格式
                String fileType = file.getContentType();
                if (fileType.equals("image/jpeg") || fileType.equals("image/png") || fileType.equals("image/jpeg")) {
                    // 要上传的目标文件存放的绝对路径
                    final String localPath="D:\\Git\\cinema\\img";
                    //上传后保存的文件名(需要防止图片重名导致的文件覆盖)
                    //获取文件名
                    String fileName = file.getOriginalFilename();
                    //获取文件后缀名
                    String suffixName = fileName.substring(fileName.lastIndexOf("."));
                    //重新生成文件名
                    fileName = UUID.randomUUID()+suffixName;
                    if (FileUtils.upload(file, localPath, fileName)) {
                        //文件存放的相对路径(一般存放在数据库用于img标签的src)
                        String relativePath="img/"+fileName;
                        result.put("relativePath",relativePath);//前端根据是否存在该字段来判断上传是否成功
                        result_msg="图片上传成功";
                    }
                    else{
                        result_msg="图片上传失败";
                    }
                }
                else{
                    result_msg="图片格式不正确";
                }
            }
            result.put("result_msg",result_msg);
            root.add(result);
        }
        String root_json= JSON.toJSONString(root);
        System.out.println(root_json);
        return root;
    }

    public static class FileUtils {

        /**
         * @param file     文件
         * @param path     文件存放路径
         * @param fileName 保存的文件名
         * @return
         */
        public static boolean upload(MultipartFile file, String path, String fileName) {

            //确定上传的文件名
            String realPath = path + "\\" + fileName;
            System.out.println("上传文件：" + realPath);

            File dest = new File(realPath);

            //判断文件父目录是否存在
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdir();
            }

            try {
                //保存文件
                file.transferTo(dest);
                return true;
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return false;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return false;
            }

        }

    }

}
